#!@TERMUX_PREFIX@/bin/bash
set -e -u

SCRIPTNAME=termux-usb
show_usage () {
    echo "Usage: $SCRIPTNAME [-l | [-r] [-E] [-e command] [device | vendorId productId]]"
    echo "List or access USB devices. Devices cannot be accessed directly,"
    echo "                 only using $SCRIPTNAME."
    echo "  -l           list available devices"
    echo "  -r           show permission request dialog if necessary"
    echo "  -e command   execute the specified command with a file descriptor"
    echo "                 referring to the device as an argument (unless -E"
    echo "                 argument is given)"
    echo "  -E           transfer file descriptor as TERMUX_USB_FD env var"
    echo "                 instead of as command line argument"
    exit 0
}

ACTION="permission"
PARAMS=""
while getopts :hlre:E option
do
    case "$option" in
        h) show_usage;;
        l) ACTION="list";;
        r) PARAMS="$PARAMS --ez request true";;
        e) ACTION="open"; export TERMUX_CALLBACK="$OPTARG";;
        E) export TERMUX_EXPORT_FD=true;;
        ?) echo "$SCRIPTNAME: illegal option -$OPTARG"; exit 1;
    esac
done
shift $((OPTIND-1))

if [ "$ACTION" == "list" ]
then
    if [ $# -gt 0 ]; then echo "$SCRIPTNAME: too many arguments"; exit 1; fi
else
    if [ $# -lt 1 ]; then
        echo "$SCRIPTNAME: missing -l or device path"
        exit 1
    elif [ $# -eq 1 ]; then
        # The device's usbfs path has been provided
        PARAMS="$PARAMS --es device $1"
    elif [ $# -eq 2 ]; then
        # A vendorId and ProductId of the device has been provided
        PARAMS="$PARAMS --es vendorId $1"
        PARAMS="$PARAMS --es productId $2"
    else
        echo "$SCRIPTNAME: too many arguments"
        exit 1
    fi
fi

CMD="@TERMUX_PREFIX@/libexec/termux-api Usb -a $ACTION $PARAMS"

if [[ "$ACTION" == "list" ]]; then
    $CMD
elif [[ "$ACTION" == "permission" ]]; then
    OUTPUT="$($CMD)"
    case "$OUTPUT" in
        "No such device"|"No such device.") echo "No such device."; exit 1;;
        "yes") echo "Permission granted."; exit 0;;
        "no"|"Permission denied.") echo "Permission denied."; exit 1;;
        "Permission request timeout.") echo "Permission request timeout."; exit 1;;
        *) printf "%s\n" "$OUTPUT"; exit 0;;
    esac
elif [[ "$ACTION" == "open" ]]; then
    OUTPUT="$($CMD)"
    case "$OUTPUT" in
        "No such device"|"No such device.") echo "No such device."; exit 1;;
        "No permission"|"Permission denied.") echo "Permission denied."; exit 1;;
        "Permission request timeout.") echo "Permission request timeout."; exit 1;;
        "Failed to open device"|"Open device failed.") echo "Open device failed."; exit 1;;
        *) printf "%s\n" "$OUTPUT"; exit 0;;
    esac
fi

exit 0
